package com.hup.utils.commons.exception.parser;

import com.hup.utils.commons.exception.AppCommonException;
import com.hup.utils.commons.exception.AppExceptionHandler;
import com.hup.utils.commons.exception.CauseException;
import com.hup.utils.commons.exception.ErrInfo;
import com.hup.utils.commons.exception.ErrParserRegister;
import com.hup.utils.commons.exception.ExceptionMsgParser;
import com.hup.utils.commons.exception.MultiException;
import com.hup.utils.commons.exception.TraceHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hugan
 * @date 2019/8/24
 */
public class CommonAppParser implements ErrParserRegister {

    @Override
    public List<ExceptionMsgParser> getParsers() {
        ArrayList<ExceptionMsgParser> list = new ArrayList<>();
        list.add(new AppCommon());
        list.add(new Cause());
        list.add(new Multi());
        return list;
    }

    private static class AppCommon implements ExceptionMsgParser<AppCommonException> {
        @Override
        public String getMsg(AppCommonException e) {
            return e.getMessage();
        }

        @Override
        public String getTrace(AppCommonException e) {
            return null;
        }
    }

    private static class Cause implements ExceptionMsgParser<CauseException> {
        @Override
        public String getMsg(CauseException e) {
            return e.getMessage();
        }

        @Override
        public String getTrace(CauseException e) {
            return TraceHandler.TRACE_HANDLER.getTrace(e.getCause());
        }
    }

    private static class Multi implements ExceptionMsgParser<MultiException> {
        @Override
        public String getMsg(MultiException e) {
            return null;
        }

        @Override
        public ErrInfo getInfo(String msgHead, MultiException e) {
            ErrInfo res = new ErrInfo();
            int count = 0;
            StringBuilder sbMsg = new StringBuilder(e.getMessage()).append('\n');
            StringBuilder sbTrace = new StringBuilder();
            for (Exception child : e.getExceptions()) {
                count++;
                ErrInfo errInfo = AppExceptionHandler.handleNoLog(child);

                sbMsg.append("错误msg").append(count).append(":");
                sbMsg.append(errInfo.getErrMsg()).append('\n');

                sbTrace.append("错误Trace").append(count);
                sbTrace.append(errInfo.getTrace()).append('\n');
            }

            res.setMsg(msgHead, sbMsg.toString());
            res.setTrace(sbTrace.toString());
            return res;
        }
    }

}
